package com.angle.im.server.utils;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

/**
 * 通用方法封装
 *
 * @author ZhuPengWei
 * @date 2018/6/27 18:04
 */
public class CommonUtils {

    /**
     * 对象转换字节数组
     *
     * @param o 对象
     * @return 字节数组
     */
    public static byte[] objToByteArr(Object o) {
        if (o instanceof String) {
            return ObjectUtil.serialize(o);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return ObjectUtil.serialize(objectMapper.writeValueAsString(o));
        } catch (JsonProcessingException e) {
            e.fillInStackTrace();
            return null;
        }
    }

    /**
     * 字节数组转换对象
     *
     * @param bytes 字节数组
     * @param clazz 对象字节码
     * @return 对象
     */
    public static <T> T byteArrToObj(byte[] bytes, Class<T> clazz) {
        String jsonStr = ObjectUtil.unserialize(bytes);
        return JSON.parseObject(jsonStr, clazz);
    }

}
